
package com.scalar.chiptrack.sales.actions;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.operations.process.FinishedGoods;
import com.scalar.chiptrack.operations.process.dao.FinishedGoodsDAO;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.sales.dao.SalesDAO;
import com.scalar.chiptrack.sales.dao.SalesOrderDAO;
import com.scalar.chiptrack.sales.dao.NewCustomerDAO;
import com.scalar.chiptrack.sales.forms.OrdersForm;
import com.scalar.chiptrack.users.User;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;


/**
 * Implementation of <strong>Action</strong> that gives customers list,
 * search with customer name, create sales order
 */

public final class ViewOrdersAction extends ChipTrackAction
{
    // ----------------------------------------------------- Instance Variables


    private static final String ACTION_NAME = "/viewOrders.do";  // Added by Basha (08/08/2003)


    // --------------------------------------------------------- Public Methods


    /**
     * Process the specified HTTP request, and create the corresponding HTTP
     * response (or forward to another web component that will create it).
     * Return an <code>ActionForward</code> instance describing where and how
     * control should be forwarded, or <code>null</code> if the response has
     * already been completed.
     *
     * @param mapping The ActionMapping used to select this instance
     * @param form The optional ActionForm bean for this request (if any)
     * @param request The HTTP request we are processing
     * @param response The HTTP response we are creating
     *
     * @exception Exception if business logic throws an exception
     */
    public ActionForward execute ( ActionMapping mapping,
                                   ActionForm form,
                                   HttpServletRequest request,
                                   HttpServletResponse response )
            throws Exception
    {
        ArrayList viewList = null;
        // Extract attributes and parameters we will need
        OrdersForm subform = ( OrdersForm ) form;
        String action = request.getParameter ( "action" );
        int isSample = 1;
        HttpSession session = request.getSession ();

        User user = ( User ) session.getAttribute ( SessionKeys.USER_KEY );

        if ( user == null )
        {
            session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString () );
            return ( mapping.findForward ( "login" ) );
        }

        HashMap errors = new HashMap ();
        HashMap info = new HashMap ();

        if ( action == null )
            request.setAttribute ( "showList", "FALSE" );

       if ( "SearchOrder".equals ( action ) )
        {
            String customerId = ( String ) BeanUtils.getSimpleProperty ( form, "customerId" );
            String marketingPartNo = request.getParameter ( "manufacturingPartNo" );
            String fromDate = ( String ) BeanUtils.getSimpleProperty ( form, "fromDate" );
            String toDate = ( String ) BeanUtils.getSimpleProperty ( form, "toDate" );
            String status = ( String ) BeanUtils.getSimpleProperty ( form, "status" );
            String salesOrderNo = ( String ) BeanUtils.getSimpleProperty ( form, "salesOrderId" );
            String endCustomer =  ( String ) BeanUtils.getSimpleProperty ( form, "endCustomer" );
            String endUser =  ( String ) BeanUtils.getSimpleProperty ( form, "endUser" );
            String customerPO = (String) BeanUtils.getSimpleProperty ( form, "customerPO" );
            int year = 0;
            if ( ( request.getParameter ( "year" ) != null ) && ( request.getParameter ( "year" ).trim ().length () != 0 ) )
            {
                try
                {
                    year = Integer.parseInt ( request.getParameter ( "year" ) );
                }
                catch ( NumberFormatException nfe )
                {
                    year = 0;
                }
            }

            //This session attribute is being set to indicate that the view order page has been called.
            //This will be used in approve missed order of approveOrderAction to check whether the request has originated from view orders or not
            session.setAttribute ( "ViewOrderRequest", "true" );
            session.removeAttribute ( "SalesOrderHoldReleaseRequest" );

            if ( ( request.getParameter ( "isSample" ) != null ) && ( request.getParameter ( "isSample" ).length () != 0 ) )
            {
                try
                {
                    isSample = Integer.parseInt ( request.getParameter ( "isSample" ) );
                }
                catch ( NumberFormatException nfe )
                {
                }
                finally
                {
                }
            }

            viewList = SalesDAO.loadViewOrderLineItems ( salesOrderNo, customerId, marketingPartNo, isSample, status, year, endCustomer, endUser, customerPO, user  );
            request.setAttribute ( "customerList", CustomerDAO.getAllCustomerNamesByUserTypeByCustomerType (null,user,isSample) );
            request.setAttribute ( "productList", loadManufacturingProducts () );

            request.setAttribute ( "years", SalesOrderDAO.getYearList () );
            request.setAttribute ( "endCustomerList", NewCustomerDAO.loadAllEndCustomersWithSOEndcustomersByUserType(null,-1,false,user) );
            request.setAttribute ( "endUserList", NewCustomerDAO.loadAllEndUsersByUserType(null,-1, false,user) );
            request.setAttribute ( "salesOrdersList", SalesOrderDAO.loadAllSalesOrderIds(isSample, "AllSalesOrders" ));
            request.setAttribute ( "posList", SalesOrderDAO.loadAllCustomerPOs(isSample, "AllSalesOrders"));

            if ( viewList.size () == 0 )
            {
                if ( marketingPartNo == null || marketingPartNo.trim ().length () == 0 )
                    marketingPartNo = "0";
                if ( customerId == null )
                    customerId = "0";
                if ( salesOrderNo == null || salesOrderNo.trim ().length () == 0 )
                    salesOrderNo = "0";
                int booking_year = 0;
                try
                {
                    booking_year = Integer.parseInt(  subform.getYear() );
                }
                catch ( NumberFormatException e )
                {
                    booking_year = 0;
                }

                String salesOrderInfo = SalesDAO.getSalesOrderStatus ( null, marketingPartNo, customerId, salesOrderNo, status, isSample, endUser, booking_year, user.getUserId());

                if ( salesOrderInfo == null || salesOrderInfo.trim ().length () == 0 )
                {
                    errors.put ( ERROR_SALES_ORDER_NOT_FOUND_WITH_GIVEN_SEARCH_CRITERIA, null );
                }

                else
                {
                    errors.put ( salesOrderInfo, null );
                }

            }
            else
            {
                request.setAttribute ( "showList", "TRUE" );
                request.setAttribute ( "viewList", viewList );
                return ( mapping.findForward ( "success" ) );
            }
        }

        if ( "ViewOrdersList".equals ( action ) )
        {
            subform.setManufacturingPartNo ( "" );
            subform.setSalesOrderId ( ( "" ) );
            subform.setCustomerId ( 0 );
            subform.setStatus ( "ALL" );
            request.setAttribute ( "showList", "FALSE" );
        }
        if ( ( request.getParameter ( "isSample" ) != null ) && ( request.getParameter ( "isSample" ).length () != 0 ) )
        {
            try
            {
                isSample = Integer.parseInt ( request.getParameter ( "isSample" ) );
            }
            catch ( NumberFormatException nfe )
            {
            }
            finally
            {
            }
        }
        try
        {
            request.setAttribute ( "customerList", CustomerDAO.getAllCustomerNamesByUserTypeByCustomerType ( null, user, isSample ) );
            request.setAttribute ( "productList", loadManufacturingProducts () );
            request.setAttribute ( "years", SalesOrderDAO.getYearList () );
            request.setAttribute ( "endCustomerList", NewCustomerDAO.loadAllEndCustomersWithSOEndcustomersByUserType(null,-1,false,user) );
            request.setAttribute ( "endUserList", NewCustomerDAO.loadAllEndUsersByUserType(null,-1, false,user) );
            request.setAttribute ( "salesOrdersList", SalesOrderDAO.loadAllSalesOrderIds(isSample, "AllSalesOrders" ));
            request.setAttribute ( "posList", SalesOrderDAO.loadAllCustomerPOs(isSample, "AllSalesOrders"));
        }
        catch(Exception Ex)
        {
            errors.put("Error while loading the view sales Order Data", null);
        }
        if ( !errors.isEmpty () )
            request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
        if ( !info.isEmpty () )
            request.setAttribute ( SessionKeys.INFO_MESSAGES, info );

        return ( mapping.findForward ( "success" ) );
    }

    public static ArrayList loadManufacturingProducts () throws Exception
    {
        ArrayList parts = new ArrayList ();
        Iterator list = FinishedGoodsDAO.loadFinishedGoods ().iterator ();
        parts.add ( new org.apache.struts.util.LabelValueBean ( "All Products", "" ) );
        while ( list.hasNext () )
        {
            FinishedGoods product = ( FinishedGoods ) list.next ();
            parts.add ( new org.apache.struts.util.LabelValueBean ( product.getManufacturingPartNo (), product.getManufacturingPartNo () ) );
        }
        return parts;
    }

}
